package
{
	import caurina.transitions.Tweener;
	
	import com.xcopy.FileReader;
	import com.xcopy.Stats;
	import com.xcopy.UILoaderEnhancer;
	
	import fl.controls.Button;
	import fl.managers.FocusManager;
	
	import flash.display.DisplayObject;
	import flash.display.DisplayObjectContainer;
	import flash.display.MovieClip;
	import flash.display.Shape;
	import flash.display.Sprite;
	import flash.display.StageScaleMode;
	import flash.events.Event;
	import flash.events.KeyboardEvent;
	import flash.events.MouseEvent;
	import flash.events.TimerEvent;
	import flash.media.Sound;
	import flash.net.LocalConnection;
	import flash.system.System;
	import flash.text.TextField;
	import flash.text.TextFieldType;
	import flash.utils.Dictionary;
	import flash.utils.Timer;
	
	import org.osmf.display.ScaleMode;

	[SWF(width = '1000', height = '666', backgroundColor = '#666666', frameRate = '30')]
	public class NewBridge_25LineSlot extends MovieClip
	{
		// 所有的動作加起來必須為 100
		private const PERCENT_DEBUG:Number     = 10;
		private const PERCENT_TABLE:Number     = 90;
		public const INIT_GAME:String          = 'INIT_GAME';
		public const END_GAME:String           = 'END_GAME';
		public const BREAK_GAME:String         = 'BREAK_GAME';
		public const PAYMENT:String            = 'PAYMENT';
		public var txtInput:TextField          = new TextField();
		public var reader:FileReader           = new FileReader();
		public var client:FGS18Processer       = new FGS18Processer(this, true);
		public var bridge:Slot25Bridge         = new Slot25Bridge(this);
		public var loading:Slot25Loading       = new Slot25Loading(this);
		public var debug:Slot25Debugger        = new Slot25Debugger(this);
		public var coin:UILoaderEnhancer       = new UILoaderEnhancer();
		public var canvas:Slot25Canvas         = new Slot25Canvas(this);
		private const PAGE_REFRESH_TIME:Number = 15000;
		public var core:Slot25Core             = new Slot25Core(this);
		public var monitor:Stats               = new Stats();
		public var tables:Vector.<Slot25Table> = Vector.<Slot25Table>([]); // 目前有瘋狂拜金女、叢林探險
		private var loadingPercent:Dictionary  = new Dictionary(true);
		private var soundList:Vector.<Array>   = Vector.<Array>([]);
		private var swfMapping:Dictionary      = new Dictionary(true);
		public var timer:Timer                 = new Timer(PAGE_REFRESH_TIME);

		public function onTimer(e:TimerEvent):void
		{
			tables[core.currentLobby].lobby.requestPage();
		}

		public function NewBridge_25LineSlot()
		{
			this.addChild(canvas.sprite);
			loadingPercent['Debug'] = PERCENT_DEBUG;
			loadingPercent['Table'] = PERCENT_TABLE;
			reader.listen(onFileLoaded, onFileLoading, onFileMessage);
			reader.read('AD', 'http://golden.goldengame.com.tw/game_client/link02.html');
			loading.clip = new Slot25_Loading();
			canvas.addChild(loading.clip);
			reader.swallow('Debug', core.dirMain + 'debugger.swf?v=' + core.ver);
			loading.addEventListener(Slot25Loading.DONE, onLoadingDone);
			swfMapping["Debug"] = "Screen_Debug";
			swfMapping["Table0"] = "Slot25_Main_Girl";
			swfMapping["Table1"] = "Slot25_Main_Forest";
			// 拜金女的音效列表
			soundList[0] = ['1000', '1010', '1020', '1030', '1100', '1110', '1111', '1112', '1130', '1140', '1200', '1201', '1210', '1220', '1221', '1222',
				'1230', '1231', '1240', '1300', '1310', '1320', '1330', '2000', '2010', '2050', '2060'];
			// 叢林探險的音效列表
			soundList[1] = ['1000', '1010', '1020', '1030', '1100', '1110', '1111', '1112', '1130', '1140', '1200', '1201', '1210', '1220', '1221', '1222',
				'1230', '1231', '1240', '1300', '1310', '1320', '1330', '2000', '2010', '2050', '2060'];
			timer.addEventListener(TimerEvent.TIMER, onTimer);
			// 初始化各大廳物件
			var i:Number = 0;
			var table:Slot25Table;
			for (i = 0; i < core.totalLobbies; i++)
			{
				table = new Slot25Table(this);
				table.lobby.type = i;
				tables[i] = table;
			}
			coin.createOwn();
			coin.scaleContent = false;
			coin.disable();
		}

		private function addTextInput():void
		{
			canvas.addChild(coin.clip);
			canvas.addChild(txtInput);
			txtInput.width = 380;
			txtInput.height = 20;
			txtInput.x = 223;
			txtInput.y = 641;
			txtInput.maxChars = 128;
			txtInput.textColor = 0xFFFFFF;
			txtInput.type = TextFieldType.INPUT;
			txtInput.addEventListener(KeyboardEvent.KEY_DOWN, inputHandler);
		}

		private function inputHandler(event:KeyboardEvent):void
		{
			if (event.keyCode != 13 | txtInput.text.length == 0)
			{
				return;
			}
			if (txtInput.text.toUpperCase() == 'GAME18DEBUG')
			{
				txtInput.text = '';
				openDebug();
			}
			else
			{
				if (loading.clip.visible)
				{
					txtInput.text = '';
					return;
				}
				this.debug.print('>> C2S_Talk：[' + txtInput.text + ']');
				this.client.C2S_Talk(txtInput.text);
				txtInput.text = '';
			}
		}

		public function openDebug():void
		{
			debug.enable();
		}

		// 某支機台讀取完成，則檢查是否為預設機台，若是要進入遊戲
		private function onLoadingDone(e:Event):void
		{
			initGame();
		}

		private function onFileLoaded(ID:String, content:String):void
		{
			var i:int = 0;
			var length:uint;
			var temp:String;
			switch (ID)
			{
				case 'AD':
				{
					core.analyseAD(content);
					break;
				}
				case 'Debug':
				{
					debug.clip = reader.spit(ID, swfMapping[ID]);
					canvas.addChild(debug.clip);
					debug.print('Current Ver: ' + core.ver);
					debug.disable();
					addTextInput();
					// 開始讀取所有大廳
					for (i = 0; i < core.totalLobbies; i++)
					{
						reader.swallow('Table' + i, core.dirRoom + 'table' + i + '.swf?v=' + core.ver);
					}
					// 同時也讀取噴金幣動畫（非必要，讀入即可）
					coin.source = core.dirMain + 'Coin.swf?v=' + core.ver;
					break;
				}
				case 'Table0': // 瘋狂拜金女
				{
					tables[0].clip = reader.spit(ID, swfMapping[ID]);
					tables[0].disable();
					canvas.addChild(tables[0].clip);
					canvas.setChildIndex(coin.clip);
					canvas.setChildIndex(debug.clip);
					canvas.setChildIndex(txtInput);
					length = soundList[0].length;
					for (i = 0; i < length; i++)
					{
						temp = soundList[0][i];
						tables[0].addSound(temp, reader.spit('Table0', 'Sound_0_' + temp) as Sound);
					}
					tables[0].addMusic('Free', reader.spit('Table0', 'Sound_0_2050') as Sound);
					tables[0].addMusic('Lobby', reader.spit('Table0', 'Sound_0_2060') as Sound);
					break;
				}
				case 'Table1': // 叢林探險
				{
					tables[1].clip = reader.spit(ID, swfMapping[ID]);
					tables[1].disable();
					canvas.addChild(tables[1].clip);
					canvas.setChildIndex(coin.clip);
					canvas.setChildIndex(debug.clip);
					canvas.setChildIndex(txtInput);
					tables[1].girlPlay(false);
					length = soundList[0].length;
					for (i = 0; i < length; i++)
					{
						temp = soundList[0][i];
						tables[1].addSound(temp, reader.spit('Table1', 'Sound_1_' + temp) as Sound);
					}
					tables[1].addMusic('Free', reader.spit('Table1', 'Sound_1_2050') as Sound);
					tables[1].addMusic('Lobby', reader.spit('Table1', 'Sound_1_2060') as Sound);
					break;
				}
			}
		}

		// 讀取進度
		private function onFileLoading(ID:String, percent:Number):void
		{
			switch (ID)
			{
				case 'Debug':
				{
					loading.percent = Math.floor(percent / 100 * loadingPercent['Debug']);
					break;
				}
				case 'Table0':
				{
					if (core.defaultLobby == 0)
					{
						loading.percent = loadingPercent['Debug'] + Math.floor(percent / 100 * loadingPercent['Table']);
					}
					break;
				}
				case 'Table1':
				{
					if (core.defaultLobby == 1)
					{
						loading.percent = loadingPercent['Debug'] + Math.floor(percent / 100 * loadingPercent['Table']);
					}
					break;
				}
			}
		}

		private function onFileMessage(ID:String, message:String):void
		{
			switch (ID)
			{
				case 'Debug':
				{
					debug.print(message);
					break;
				}
				case 'Table0':
				case 'Table1':
				{
					debug.print(message);
					break;
				}
			}
		}

		// 將某物件提升至畫面最上層，在它前方的物件向後一層
		private function raiseChild(dp:DisplayObject):void
		{
			var total:int = this.numChildren;
			this.setChildIndex(dp, total - 1);
		}

		//	 若預設的 table 讀完，就可以進入遊戲了
		private function initGame():void
		{
			var ret:String = bridge.autoExecution();
			txtInput.visible = true;
			dispatchEvent(new Event(INIT_GAME));
		}

		public function endGame():void
		{
			txtInput.visible = false;
			core.playing = false;
			timer.stop();
			var i:Number = 0;
			for (i = 0; i < core.totalLobbies; i++)
			{
				tables[i].radio.stopMusic();
			}
			client.disconnect();
			debug.print('dispatch EndGame');
			dispatchEvent(new Event(END_GAME));
		}

		public function payGame():void
		{
			debug.print('dispatch PAYMENT');
			dispatchEvent(new Event(PAYMENT));
		}

		public function breakGame(isDispatch:Boolean = true):void
		{
			var i:Number = 0;
			for (i = 0; i < core.totalLobbies; i++)
			{
				tables[i].radio.stopMusic();
			}
			if (isDispatch)
			{
				debug.print('dispatch BreakGame');
				dispatchEvent(new Event(BREAK_GAME));
			}
		}

		// 由外部程式呼叫建立遊戲，先手動連入主機，並設定 autoLogin 為真，待連上後就會自動再繼續進行
		public function createGame(IP:String, port:Number, token:String, lang:String):void
		{
			debug.print('>> Link to (' + IP + ',' + port + ') then createGame with ' + token);
			debug.manualLink(IP, port);
			debug.autoType = 2;
			debug.token = token;
			debug.disable();
		}

		// 由外部程式呼叫工程模式，先手動連入主機，並設定 autoLogin 為真，待連上後就會自動再繼續進行
		public function createEngineer(IP:String, port:Number, token:String, prefix:String):void
		{
			debug.print('>> Link to (' + IP + ',' + port + ') then createEngineer');
			debug.manualLink(IP, port);
			debug.autoType = 1;
			debug.token = token;
			debug.disable();
		}
	}
}
